// pages/profile/edit/edit.js
Page({
  data: {
    userInfo: {
      nickName: '',
      avatarUrl: '',
      gender: 0,
      phone: '',
      email: '',
      country: '',
      province: '',
      city: ''
    },
    originalUserInfo: {},
    saving: false,
    errors: {}
  },

  onLoad() {
    this.loadUserInfo()
  },

  // 加载用户信息
  loadUserInfo() {
    const app = getApp()
    
    // 从本地存储获取用户信息
    const localUserInfo = wx.getStorageSync('userInfo') || {}
    
    // 从服务器获取最新用户信息
    this.fetchUserProfile()
    
    // 先显示本地信息
    this.setData({
      userInfo: {
        nickName: localUserInfo.nickName || '',
        avatarUrl: localUserInfo.avatarUrl || '',
        gender: localUserInfo.gender || 0,
        phone: localUserInfo.phone || '',
        email: localUserInfo.email || '',
        country: localUserInfo.country || '',
        province: localUserInfo.province || '',
        city: localUserInfo.city || ''
      }
    })
    
    // 备份原始数据
    this.setData({
      originalUserInfo: JSON.parse(JSON.stringify(this.data.userInfo))
    })
  },

  // 从服务器获取用户信息
  async fetchUserProfile() {
    try {
      const app = getApp()
      const token = wx.getStorageSync('token')
      
      if (!token) {
        wx.showToast({
          title: '请先登录',
          icon: 'error'
        })
        return
      }

      const response = await app.request({
        url: '/api/User/profile',
        method: 'GET',
        header: {
          'Authorization': `Bearer ${token}`
        }
      })

      if (response.success && response.data) {
        const serverUserInfo = response.data
        this.setData({
          userInfo: {
            nickName: serverUserInfo.nickName || '',
            avatarUrl: serverUserInfo.avatarUrl || '',
            gender: serverUserInfo.gender || 0,
            phone: serverUserInfo.phone || '',
            email: serverUserInfo.email || '',
            country: serverUserInfo.country || '',
            province: serverUserInfo.province || '',
            city: serverUserInfo.city || ''
          }
        })
        
        // 更新备份数据
        this.setData({
          originalUserInfo: JSON.parse(JSON.stringify(this.data.userInfo))
        })
        
        // 更新本地存储
        wx.setStorageSync('userInfo', this.data.userInfo)
      }
    } catch (error) {
      console.error('获取用户信息失败:', error)
    }
  },

  // 选择头像
  chooseAvatar() {
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePath = res.tempFiles[0].tempFilePath
        
        // 上传头像
        this.uploadAvatar(tempFilePath)
      },
      fail: (err) => {
        console.log('选择头像失败', err)
      }
    })
  },

  // 上传头像
  async uploadAvatar(filePath) {
    try {
      wx.showLoading({ title: '上传中...' })
      
      const app = getApp()
      const token = wx.getStorageSync('token')
      
      // 这里应该调用文件上传API，暂时使用本地路径
      this.setData({
        'userInfo.avatarUrl': filePath
      })
      
      wx.hideLoading()
      wx.showToast({
        title: '头像更新成功',
        icon: 'success'
      })
    } catch (error) {
      wx.hideLoading()
      wx.showToast({
        title: '头像上传失败',
        icon: 'error'
      })
      console.error('上传头像失败:', error)
    }
  },

  // 昵称输入
  onNickNameInput(e) {
    const value = e.detail.value
    this.setData({
      'userInfo.nickName': value
    })
    this.clearError('nickName')
  },

  // 性别选择
  onGenderChange(e) {
    const gender = parseInt(e.currentTarget.dataset.gender)
    this.setData({
      'userInfo.gender': gender
    })
  },

  // 手机号输入
  onPhoneInput(e) {
    const value = e.detail.value
    this.setData({
      'userInfo.phone': value
    })
    this.clearError('phone')
  },

  // 邮箱输入
  onEmailInput(e) {
    const value = e.detail.value
    this.setData({
      'userInfo.email': value
    })
    this.clearError('email')
  },

  // 选择地区
  chooseRegion() {
    wx.chooseLocation({
      success: (res) => {
        // 解析地址信息
        const address = res.address || ''
        const addressParts = address.split(/[省市区县]/)
        
        this.setData({
          'userInfo.country': '中国',
          'userInfo.province': addressParts[0] + '省',
          'userInfo.city': addressParts[1] + '市'
        })
      },
      fail: (err) => {
        console.log('选择地区失败', err)
      }
    })
  },

  // 表单验证
  validateForm() {
    const { userInfo } = this.data
    const errors = {}

    // 验证昵称
    if (!userInfo.nickName || userInfo.nickName.trim() === '') {
      errors.nickName = '请输入昵称'
    } else if (userInfo.nickName.length > 20) {
      errors.nickName = '昵称长度不能超过20个字符'
    }

    // 验证手机号
    if (userInfo.phone && !/^1[3-9]\d{9}$/.test(userInfo.phone)) {
      errors.phone = '手机号格式不正确'
    }

    // 验证邮箱
    if (userInfo.email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(userInfo.email)) {
      errors.email = '邮箱格式不正确'
    }

    this.setData({ errors })
    return Object.keys(errors).length === 0
  },

  // 清除错误信息
  clearError(field) {
    const errors = { ...this.data.errors }
    delete errors[field]
    this.setData({ errors })
  },

  // 保存用户信息
  async saveProfile() {
    if (!this.validateForm()) {
      wx.showToast({
        title: '请检查输入信息',
        icon: 'error'
      })
      return
    }

    this.setData({ saving: true })

    try {
      const app = getApp()
      const token = wx.getStorageSync('token')
      
      if (!token) {
        wx.showToast({
          title: '请先登录',
          icon: 'error'
        })
        return
      }

      const { userInfo } = this.data
      const updateData = {
        nickName: userInfo.nickName,
        avatarUrl: userInfo.avatarUrl,
        gender: userInfo.gender,
        phone: userInfo.phone || null,
        email: userInfo.email || null
      }

      const response = await app.request({
        url: '/api/User/profile',
        method: 'PUT',
        data: updateData,
        header: {
          'Authorization': `Bearer ${token}`
        }
      })

      if (response.success) {
        // 更新本地存储
        wx.setStorageSync('userInfo', userInfo)
        
        wx.showToast({
          title: '保存成功',
          icon: 'success'
        })
        
        // 延迟返回上一页
        setTimeout(() => {
          wx.navigateBack()
        }, 1500)
      } else {
        wx.showToast({
          title: response.message || '保存失败',
          icon: 'error'
        })
      }
    } catch (error) {
      console.error('保存用户信息失败:', error)
      wx.showToast({
        title: '保存失败',
        icon: 'error'
      })
    } finally {
      this.setData({ saving: false })
    }
  },

  // 页面卸载时检查是否有未保存的更改
  onUnload() {
    const { userInfo, originalUserInfo } = this.data
    const hasChanges = JSON.stringify(userInfo) !== JSON.stringify(originalUserInfo)
    
    if (hasChanges) {
      // 这里可以提示用户是否保存更改
      console.log('用户有未保存的更改')
    }
  }
})